<template>
  <div class="player">
    <audio
      :src="musicUrl"
      ref="audioPlayer"
      autoplay
      @play="changeState(true)"
      @pause="changeState(false)"
      @ended="changePlayer('next')"
      @timeupdate="timeupdate"
    ></audio>
    <div class="left">
      <div class="avatar" @click="isShow">
        <img :src="musicDeteil.al.picUrl" alt="" v-if="musicDeteil.al" />
        <img src="@/assets/img/test.jpg" alt="" v-else />
      </div>
      <div class="userInfo" v-if="musicDeteil && musicDeteil.name">
        <div class="singName">{{ musicDeteil.name }}</div>
        <div class="userName">
          <span class="name">{{ musicDeteil.ar[0].name }}</span>
          <i class="el-icon-download" @click="download"></i>
        </div>
      </div>
    </div>
    <div class="center">
      <div class="button">
        <span
          class="type"
          @click="playType = playType === 'random' ? 'order' : 'random'"
        >
          <!-- 循环模式 -->
          <i class="el-icon-refresh-right" v-if="playType === 'order'"></i>
          <i class="el-icon-sort" v-else></i>
        </span>
        <span
          class="prev"
          @click="musicList.length != 0 ? changePlayer('pre') : ''"
        >
          <!-- 上一首 -->
          <i class="el-icon-caret-left"></i>
        </span>
        <span class="play" @click="musicList.length != 0 ? handlePlay() : ''">
          <!-- 暂停播放 -->
          <i class="el-icon-video-play" v-if="!this.$store.state.isPlay"></i>
          <i class="el-icon-video-pause" v-else></i>
        </span>
        <span
          class="next"
          @click="musicList.length != 0 ? changePlayer('next') : ''"
        >
          <!-- 下一首 -->
          <i class="el-icon-caret-right"></i>
        </span>
        <span class="like" @click="clickLike()">
          <!-- 喜欢 不喜欢 -->
          <i
            class="el-icon-star-off"
            :class="isUserLikeCurrentMusic ? 'likeBtn' : ''"
          ></i>
        </span>
      </div>
      <div class="plan">
        <span class="timeStart">{{ currentTime | handleMusicTime }}</span>
        <el-slider
          v-model="timeProgress"
          :show-tooltip="false"
          @change="changeProgress"
          :disabled="musicList.length == 0"
          class="sliderLong"
        ></el-slider>
        <span class="timeOver">{{ duration }}</span>
      </div>
    </div>
    <div class="right">
      <div class="top">
        <i class="el-icon-headset" @click="changeMute"></i>
        <div class="volumeNone1" v-if="isMuted"></div>
        <div class="volumeNone2" v-if="isMuted"></div>
        <el-slider
          @input="changeVolume"
          v-model="volume"
          :show-tooltip="false"
          class="volume"
        >
        </el-slider>
        <div class="drawer"><i class="el-icon-bank-card"></i></div>
      </div>
      <div class="bottom">create By 20231008</div>
    </div>
  </div>
</template>
<script>
import { getMusicUrl, isLikeMusic, getLikeMusicList } from '@/api/music/music'
import { returnSecond, handleMusicTime } from '@/plugins/utils'
export default {
  name: 'playerPage',
  data() {
    return {
      // 进度条的位置
      timeProgress: 0,
      // 音量
      volume: 30,
      // 保存当前音量
      volumeSave: 0,
      // 当前播放时间位置
      currentTime: '00:00',
      // 音乐总时长
      duration: '00:00',
      // 总秒数 用来算进度条位置 当前秒数/总秒数
      durationNum: 0,
      // 最后的时间，用来节流进度的变化
      lastSecond: 0,

      musicUrl: '',
      // 当前播放歌曲index序号
      currentMusicIndex: 0,
      // 当前歌曲详情
      musicDeteil: {},
      // 播放模式（顺序播放，随机播放）
      // order random
      playType: 'order',
      musicList: [], //音乐列表
      // 用户的喜欢音乐列表
      likeMuiscList: [],
      // 用户是否喜欢当前音乐
      isUserLikeCurrentMusic: false,
      // 是否静音
      isMuted: false,
      // 当前音乐类型，用于下载
      musicType: '',
      // 音乐卡片状态 false 关 true开
      musicCardType: false
    }
  },
  methods: {
    // 播放音乐的函数
    playMusic() {
      this.$refs.audioPlayer.play()
    },
    // 暂停音乐的函数
    pauseMusic() {
      this.$refs.audioPlayer.pause()
    },
    // 点击暂停播放
    handlePlay() {
      this.$store.state.isPlay ? this.pauseMusic() : this.playMusic()
    },
    // audio开始或暂停播放的回调  在vuex中改变状态
    changeState(state) {
      this.$store.commit('changePlayState', state)
    },
    // 请求歌曲的url
    async getMusicDetail(id) {
      try {
        this.$store.commit('updateMusicLoadState', true)
        let res = await getMusicUrl(id)
        if (res.data.data[0].url === null) {
          this.$message.error('该歌曲暂无版权，将为您播放下一首歌曲')
          this.changeMusic('next')
          return
        }
        // console.log(res)
        this.musicUrl = res.data.data[0].url
        this.musicType = res.data.data[0].type.toLowerCase()
        this.$store.commit('updateMusicLoadState', false)
      } catch (err) {
        this.$message.error('无版权!')
        console.log(err)
      }
    },
    // 根据id在音乐列表中获取正在播放的歌曲信息
    async getMusicDetailFromMusicList() {
      let index = this.musicList.findIndex(
        (item) => item.id === this.$store.state.musicId
      )
      // console.log(id)
      if (index !== -1) {
        // 记录当前的音乐index序号
        this.currentMusicIndex = index
        // 保存至vuex
        this.$store.commit('updateCurrentIndex', index)
        this.musicDeteil = this.musicList[index]
        this.duration = this.musicList[index].dt
      }
    },
    // 切歌
    changePlayer(type, id) {
      if (type === 'click') {
        // 点击抽屉 自动播放下一首
        // console.log('点击抽屉了')
        // console.log(id)
        this.$store.commit('updateMusicId', id)
      } else if (type === 'pre') {
        // 上一首
        // 1.确定当前歌曲的索引是歌单中的索引
        let currentMusicIndex = this.currentMusicIndex
        // 2.创建上一首的歌曲索引
        let preIndex
        // console.log(1, preIndex)
        // 3.判断播放类型
        if (this.playType === 'order') {
          // 顺序播放  如果上一个歌曲的索引小于0 就把最后一首歌的索引赋值给perIndex 如果上一个歌曲的索引大于0 就正常减一
          preIndex =
            currentMusicIndex - 1 < 0
              ? this.musicList.length - 1
              : currentMusicIndex - 1
          // console.log(2, preIndex)
        } else if (this.playType === 'random') {
          // 随机播放
          // 3.1 看音乐列表是否只有一首歌 ，如果只有一首歌就播这一首
          if (this.musicList.length === 1) {
            preIndex = currentMusicIndex
          } else {
            preIndex = currentMusicIndex
            while (preIndex === currentMusicIndex) {
              preIndex = Math.floor(Math.random() * this.musicList.length)
            }
          }
        }
        // 更新播放的歌曲
        // console.log(3, preIndex)
        this.$store.commit('updateMusicId', this.musicList[preIndex].id)
      } else if (type === 'next') {
        // 下一首
        let currentMusicIndex = this.currentMusicIndex
        let nextIndex
        if (this.playType === 'order') {
          nextIndex =
            currentMusicIndex + 1 === this.musicList.length
              ? 0
              : currentMusicIndex + 1
        } else if (this.playType === 'random') {
          if (this.musicList.length === 1) {
            nextIndex = currentMusicIndex
          } else {
            nextIndex = currentMusicIndex
            while (nextIndex === currentMusicIndex) {
              nextIndex = Math.floor(Math.random() * this.musicList.length)
            }
          }
        }
        // 更新播放的歌曲
        // console.log(nextIndex)
        this.$store.commit('updateMusicId', this.musicList[nextIndex].id)
      }
    },
    // 是否添加喜欢
    async likeMusic(id, like) {
      const res = await isLikeMusic({ id, like })
      if (res.data.code === 200) {
        console.log('添加成功')
      } else {
        console.log('添加失败')
      }
    },
    // 点击添加喜欢
    async clickLike() {
      if (!localStorage.getItem('userId')) {
        this.$message.error('请先登录!')
        return
      }
      this.isUserLikeCurrentMusic = !this.isUserLikeCurrentMusic // 喜欢
      await this.likeMusic(
        this.$store.state.musicId,
        this.isUserLikeCurrentMusic
      )
      await this.getLikeMusicList()
    },
    // 获取喜欢列表
    async getLikeMusicList() {
      const timeStamp = Date.parse(new Date())
      const res = await getLikeMusicList({
        uid: localStorage.getItem('userId'),
        timeStamp
      })
      this.likeMuiscList = res.data.ids
      // console.log(this.likeMuiscList)
      // 保存vuex
      this.$store.commit('updateLikeMusicList', this.likeMuiscList)
    },
    // 判断当前歌曲是否是用户添加到喜欢的
    getIsUserLikeCurrentMusic() {
      // console.log(123464)
      // 为什么切歌没有判断喜欢按钮没有添加颜色
      // this.likeMuiscList还没有初始化 进页面先调用获取喜欢列表
      this.isUserLikeCurrentMusic = this.likeMuiscList.find((item) => {
        // console.log(item, this.$store.state.musicId)
        return item == this.$store.state.musicId
      })
    },
    // 播放器时间进度
    timeupdate() {
      // console.log(this.$refs.audioPlayer.currentTime)
      // 实时的播放时间 this.$refs.audioPlayer.currentTime
      let time = this.$refs.audioPlayer.currentTime
      this.$store.commit('updateCurrentTime', time)
      if (time !== this.lastSecond) {
        this.lastSecond = time
        this.currentTime = time // 当前时间
        this.timeProgress = Math.floor((time / this.durationNum) * 100)
      }
    },
    // 拖动进度条时间
    changeProgress(time) {
      // console.log(time)
      this.currentTime = Math.floor((time / 100) * this.durationNum)
      this.$refs.audioPlayer.currentTime = this.currentTime
    },
    // 拖动音量
    changeVolume(value) {
      this.$refs.audioPlayer.volume = value / 100 // 音量0-1之间，0静音1最大
      if (value > 0) {
        this.isMuted = false
      } else if (value === 0) {
        this.isMuted = true
      }
    },
    // 点击喇叭切换静音模式
    changeMute() {
      if (this.isMuted) {
        // 解除静音恢复当前音量
        this.volume = this.volumeSave
      } else {
        // 开始静音
        this.volumeSave = this.volume
        this.volume = 0
      }
      this.isMuted = !this.isMuted
    },
    // 下载
    async download() {
      const musicUrl = this.musicUrl
      // console.log(res.data.data[0].url)
      // 匹配资源的域名
      let url = musicUrl.match(/http.*?\.net/)
      // console.log(url)
      // 匹配域名名称，并匹配对应的代理
      let serve = url[0].match(/http:\/(\S*).music/)[1]
      // console.log(serve)
      // 截取后面的参数
      let params = musicUrl.slice(url[0].length)
      if (
        serve != '/m7' &&
        serve != '/m701' &&
        serve != '/m8' &&
        serve != '/m801'
      ) {
        // 没有对应的代理
        this.$message.error('匹配不到对应的代理,下载失败!')
        return
      }
      // console.log(params)
      if (musicUrl === null) {
        this.$message.warning('暂时无法获取资源')
      }
      let downloadMusicInfo = {
        url: serve + params,
        name:
          this.musicDeteil.name +
          ' - ' +
          this.musicDeteil.ar[0].name +
          '.' +
          this.musicType
      }
      // console.log(downloadMusicInfo)
      // this.$message.success('下载成功!')
      this.$store.commit('updateDownloadMusicInfo', downloadMusicInfo)
    },
    // 开启音乐卡片
    isShow() {
      // 清除背景mv
      this.$store.commit('updateMusicCardMv', '')
      if (!this.$store.state.musicisShow) {
        this.musicCardType = true
      } else {
        this.musicCardType = !this.musicCardType
      }

      // console.log(this.musicCardType)
      this.$store.commit('updateMusicIsshow', this.musicCardType)
    }
  },
  watch: {
    '$store.state.musicId'(id) {
      // console.log('vuex中的id发生了变化')
      // 先暂停当前播放的音乐
      this.pauseMusic()
      this.musicList = this.$store.state.musicList
      this.getMusicDetailFromMusicList()
      this.getMusicDetail(id)
      // console.log(id)
      this.durationNum = returnSecond(this.duration) // 分钟00:00 格式转换成秒
      // 判断用户是否喜欢当前音乐
      this.getIsUserLikeCurrentMusic()
      // console.log(this.$refs.audioPlayer);
    },
    '$store.state.isLogin'(current) {
      // console.log(current)
      if (current) {
        // console.log('获取喜欢列表')
        this.getLikeMusicList()
      } else {
        // 清空喜欢列表
        this.likeMuiscList = []
      }
    }
  },
  created() {
    // 获取喜欢列表
    if (this.$store.state.isLogin) this.getLikeMusicList()
  },
  filters: {
    // 过滤器 处理播放器时间格式
    handleMusicTime
  }
}
</script>
<style lang="scss" scoped>
.player {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #ccc;
  z-index: 999;
}
.left {
  display: flex;
  align-items: center;
  img {
    width: 50px;
    margin-top: 5px;
    border-radius: 10px;
    cursor: pointer;
    margin-right: 10px;
  }
  .userInfo {
    width: 100px;
    font-size: 14px;
    color: #000;
    .singName {
      text-wrap: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .userName {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 3px;
      .name {
        text-wrap: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      i {
        font-size: 20px;
        color: #666;
        cursor: pointer;
      }
    }
  }
}
.center {
  width: 415px;
  background-color: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  .button {
    display: flex;
    align-items: center;
  }
  .type {
    margin-right: 40px;
    font-size: 20px;
    cursor: pointer;
  }
  .prev {
    margin-right: 30px;
    font-size: 25px;
    cursor: pointer;
  }
  .play {
    margin-right: 30px;
    font-size: 28px;
    cursor: pointer;
  }
  .next {
    margin-right: 40px;
    font-size: 25px;
    cursor: pointer;
  }
  .like {
    font-size: 20px;
    cursor: pointer;
  }
  .plan {
    display: flex;
    width: 100%;
    height: 25px;
    justify-content: center;
    align-items: center;
    .sliderLong {
      width: 300px;
      margin: 0 8px;
      margin-top: 2px;
    }
    .timeStart,
    .timeOver {
      font-size: 14px;
      color: #999;
    }
  }
}
.right {
  .top {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    position: relative;
    .volumeNone1,
    .volumeNone2 {
      position: absolute;
      top: 28px;
      right: 109px;
      width: 9px;
      height: 2px;
      background-color: #252525;
      transform: rotate(-45deg);
    }
    .volumeNone2 {
      transform: rotate(45deg);
    }
    .el-icon-headset {
      margin-right: 10px;
    }
    .el-icon-headset,
    .el-icon-bank-card {
      cursor: pointer;
    }
    .volume {
      width: 50px;
      margin: 0 10px 0 8px;
    }
  }
  .bottom {
    font-size: 14px;
    color: #666;
  }
}
.likeBtn {
  color: #ec4141 !important;
}
</style>
